package com.cbtx.utils

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.telephony.TelephonyManager
import android.text.TextUtils
import java.lang.reflect.Method

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/7/1 1:03 PM
 * desc   :
 */
object SimUtil {
    /**
     * 反射获取 getSubscriberId ，既imsi
     *
     * @param subId
     * @return
     */
    fun getSubscriberId(context: Context, subId: Int): String? {
        val telephonyManager = context
            .getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager // 取得相关系统服务
        var telephonyManagerClass: Class<*>? = null
        var imsi: String? = null
        try {
            telephonyManagerClass = Class.forName("android.telephony.TelephonyManager")
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                val method =
                    telephonyManagerClass.getMethod("getSubscriberId", Int::class.javaPrimitiveType)
                imsi = method.invoke(telephonyManager, subId) as String
            } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
                val method =
                    telephonyManagerClass.getMethod("getSubscriberId", Long::class.javaPrimitiveType)
                imsi = method.invoke(telephonyManager, subId.toLong()) as String
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return imsi
    }

    /**
     * 反射获取 getSubscriptionId ，既 subid
     *
     * @param slotId 卡槽位置（0，1）
     * @return
     */
    fun getSubscriptionId(context: Context?, slotId: Int): Int {
        try {
            val datamethod: Method
            val setsubid = -1 //定义要设置为默认数据网络的subid
            //获取默认数据网络subid   getDefaultDataSubId
            val SubscriptionManager =
                Class.forName("android.telephony.SubscriptionManager")
            datamethod = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // >= 24  7.0
                SubscriptionManager.getDeclaredMethod("getDefaultDataSubscriptionId")
            } else {
                SubscriptionManager.getDeclaredMethod("getDefaultDataSubId")
            }
            datamethod.isAccessible = true
            val SubId = datamethod.invoke(SubscriptionManager) as Int
            val subManagermethod =
                SubscriptionManager.getDeclaredMethod("from", Context::class.java)
            subManagermethod.isAccessible = true
            val subManager = subManagermethod.invoke(SubscriptionManager, context)

            //getActiveSubscriptionInfoForSimSlotIndex  //获取卡槽0或者卡槽1  可用的subid
            val getActivemethod = SubscriptionManager.getDeclaredMethod(
                "getActiveSubscriptionInfoForSimSlotIndex", Int::class.javaPrimitiveType
            )
            getActivemethod.isAccessible = true
            val msubInfo = getActivemethod.invoke(subManager, slotId) //getSubscriptionId
            val SubInfo = Class.forName("android.telephony.SubscriptionInfo")

            //slot0   获取卡槽0的subid
            var subid = -1
            if (msubInfo != null) {
                val getSubId0 = SubInfo.getMethod("getSubscriptionId")
                getSubId0.isAccessible = true
                subid = getSubId0.invoke(msubInfo) as Int
            }
            return subid
        } catch (e: Exception) {
        }
        return -1
    }

    /**
     * 获取运营商 IMSI
     * 默认为 IMEI1对应的 IMSI
     *
     * @return
     */
    fun getSimOperator(context: Context): String? {
        val telephonyManager = context
            .getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager // 取得相关系统服务
        return telephonyManager.simOperator
    }

    /**
     * 根据卡槽位置 获取运营商 IMSI
     *
     * @param slotId 卡槽位置（0，1）
     * @return
     */
    fun getSimOperator(context: Context, slotId: Int): String? {
        val subid = getSubscriptionId(context, slotId)
        if (subid == -1) {
            return ""
        }
        val imsi = getSubscriberId(context, subid)
        return if (!TextUtils.isEmpty(imsi)) {
            imsi
        } else ""
    }

    /**
     * 通过卡槽位置拿 IMEI
     *
     * @param slotId (0, 1卡槽位置）
     * @return
     */
    @SuppressLint("MissingPermission")
    fun getImei(context: Context, slotId: Int): String? {
        if (slotId != 0 && slotId != 1) {
            return null
        }
        val tm =
            context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            tm.getDeviceId(slotId)
        } else if (slotId == 0) {
            tm.deviceId
        } else {
            val telephonyManager = context
                .getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager // 取得相关系统服务
            var telephonyManagerClass: Class<*>? = null
            var imei: String? = null
            try {
                telephonyManagerClass = Class.forName("android.telephony.TelephonyManager")
                val method =
                    telephonyManagerClass.getMethod("getImei", Int::class.javaPrimitiveType)
                imei = method.invoke(telephonyManager, slotId) as String
            } catch (e: Exception) {
                e.printStackTrace()
            }
            imei
        }
    }
}